package cn.huibangbang.easyexcel.controller;

import cn.huibangbang.easyexcel.domain.Student;
import cn.huibangbang.easyexcel.listener.WebStudentListener;
import cn.huibangbang.easyexcel.service.StudentService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhang
 * @version 1.0
 * @description TODO
 * @date 2023/6/28 0028
 */
@RequiredArgsConstructor
@RequestMapping("/student")
@Controller
public class StudentController {

    private final WebStudentListener webStudentListener;

    @RequestMapping("/readExcel")
    @ResponseBody
    public String readExcel(@RequestPart MultipartFile uploadExcel) {
        try {
            // 工作簿
            ExcelReaderBuilder readWorkBook = EasyExcel.read(uploadExcel.getInputStream(), Student.class, webStudentListener);
            // 工作表
            readWorkBook.sheet().doRead();
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        }
    }

    @RequestMapping("/writerExcel")
    @ResponseBody
    public void writerExcel(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");

        ServletOutputStream os = response.getOutputStream();
        // 获得一个工作簿对象
        ExcelWriterBuilder writeWorkBook = EasyExcel.write(os, Student.class);
        // 获得一个工作表对象
        ExcelWriterSheetBuilder sheet = writeWorkBook.sheet();
        // 写入内容到工作表中
        sheet.doWrite(initDate());
    }

    public static List<Student> initDate() {
        List<Student> students = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Student s = new Student();
            s.setName("王语纯" + i);
            s.setGender("male");
            s.setBirthday(new Date());
            students.add(s);
        }
        return students;
    }
}
